<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>汉字自由联想心理分析 - 分析结果</title>
  <!-- Tailwind CSS -->
  <script src="https://cdn.tailwindcss.com"></script>
  <!-- Font Awesome -->
  <link href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css" rel="stylesheet">
  <!-- Markdown解析库 -->
  <script src="https://cdn.jsdelivr.net/npm/marked/marked.min.js"></script>
  <!-- 自定义配置 -->
  <script>
    tailwind.config = {
      theme: {
        extend: {
          colors: {
            primary: '#4A6FA5',
            secondary: '#6B8EAF',
            accent: '#E76F51',
          },
        },
      }
    }
  </script>
  <style type="text/tailwindcss">
    @layer utilities {
      .content-auto {
        content-visibility: auto;
      }
      .fade-in {
        animation: fadeIn 0.8s ease-in;
      }
      @keyframes fadeIn {
        from { opacity: 0; transform: translateY(20px); }
        to { opacity: 1; transform: translateY(0); }
      }
      .result-section {
        border-left: 3px solid #4A6FA5;
        padding-left: 1rem;
        margin-left: 0.5rem;
      }
      .share-btn-hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);
      }
      /* 添加CSS样式来确保markdown内容不会超出屏幕宽度 */
      .markdown-container {
        word-wrap: break-word;
        overflow-wrap: break-word;
      }
      .markdown-container h1,
      .markdown-container h2,
      .markdown-container h3,
      .markdown-container h4,
      .markdown-container h5,
      .markdown-container h6 {
        word-wrap: break-word;
        overflow-wrap: break-word;
        hyphens: auto;
      }
      .markdown-container p,
      .markdown-container ul,
      .markdown-container ol {
        word-wrap: break-word;
        overflow-wrap: break-word;
      }
    }
  </style>
</head>
<body class="bg-gray-50 min-h-screen flex flex-col">
  <div class="container mx-auto px-4 py-8 max-w-md flex-grow">
    <!-- 返回按钮 -->
    <div class="mb-8">
      <button id="back-button" class="text-primary hover:text-primary/80 transition-colors">
        <i class="fa fa-arrow-left mr-2"></i>返回
      </button>
    </div>

    <!-- 页面标题 -->
    <h1 class="text-2xl font-bold text-center text-primary mb-8 fade-in">汉字自由联想心理分析</h1>

    <!-- 用户信息卡片 -->
    <div class="bg-white rounded-xl shadow-md p-6 mb-8 fade-in">
      <div class="flex items-center mb-4">
        <div class="w-12 h-12 bg-primary/10 rounded-full flex items-center justify-center mr-4">
          <i class="fa fa-user text-primary text-xl"></i>
        </div>
        <div>
          <p class="text-gray-700"><span class="font-medium">性别：</span><span id="user-gender">男</span></p>
          <p class="text-gray-700"><span class="font-medium">年龄：</span><span id="user-age">36</span>岁</p>
        </div>
      </div>
      
      <div class="mb-4">
        <p class="text-gray-700 mb-1"><span class="font-medium">联想汉字：</span></p>
        <p id="recognized-chars" class="text-gray-600 break-words">欢欢欢欢欢欢欢欢欢欢欢欢欢欢欢欢欢欢欢欢欢欢欢欢欢欢欢欢欢欢欢欢</p>
      </div>
      
      <p class="text-gray-500 text-sm"><span class="font-medium">分析时间：</span><span id="analysis-time">2024.08.09 12:32</span></p>
    </div>

    <!-- 分析结果标题 -->
    <h2 class="text-xl font-bold text-accent mb-4 fade-in">分析结果：</h2>

    <!-- 分析结果内容 -->
    <div class="bg-white rounded-xl shadow-md p-6 mb-12 fade-in">
      <div id="analysis-result" class="result-section mb-8">
        <!-- 这里将通过JavaScript渲染markdown格式的分析报告 -->
        <div id="loading-container" class="text-center py-12">
          <div class="animate-spin rounded-full h-16 w-16 border-b-4 border-primary mx-auto mb-6"></div>
          <p class="text-lg text-gray-600 font-medium">正在进行深度分析...</p>
          <p class="text-gray-500 mt-2">预计需要2-3分钟时间，请耐心等待</p>
          <p class="text-sm text-gray-400 mt-4">（此过程会调用AI大模型进行复杂计算）</p>
        </div>
        <div id="result-content" class="hidden"></div>
      </div>
    </div>

    <!-- 互动区域 -->
    <div class="bg-white rounded-xl shadow-md p-6 mb-8">
      <div class="flex items-center mb-4">
        <i class="fa fa-comment text-primary mr-3"></i>
        <h3 class="text-lg font-bold text-primary">继续向汉字心智AI测评提问</h3>
      </div>
      <div class="flex">
        <input type="text" class="flex-1 px-4 py-3 border border-gray-300 rounded-l-lg focus:outline-none focus:ring-2 focus:ring-primary focus:border-transparent" placeholder="请输入您的问题...">
        <button class="bg-primary text-white px-4 rounded-r-lg hover:bg-primary/90 transition-colors">
          <i class="fa fa-paper-plane"></i>
        </button>
      </div>
    </div>

    <!-- 分享按钮 -->
    <div class="flex justify-center space-x-6 mb-8">
      <button class="flex flex-col items-center text-gray-600 hover:text-primary transition-all">
        <div class="w-12 h-12 bg-blue-100 rounded-full flex items-center justify-center mb-2 hover:share-btn-hover">
          <i class="fa fa-weixin text-xl"></i>
        </div>
        <span class="text-sm">微信</span>
      </button>
      <button class="flex flex-col items-center text-gray-600 hover:text-primary transition-all">
        <div class="w-12 h-12 bg-blue-100 rounded-full flex items-center justify-center mb-2 hover:share-btn-hover">
          <i class="fa fa-weibo text-xl"></i>
        </div>
        <span class="text-sm">微博</span>
      </button>
      <button class="flex flex-col items-center text-gray-600 hover:text-primary transition-all">
        <div class="w-12 h-12 bg-blue-100 rounded-full flex items-center justify-center mb-2 hover:share-btn-hover">
          <i class="fa fa-download text-xl"></i>
        </div>
        <span class="text-sm">保存</span>
      </button>
    </div>
  </div>

  <!-- 页脚 -->
  <footer class="py-6 text-center text-gray-500 text-sm">
    <p>© 2024 汉字心智测评 | 仅供参考，非专业心理诊断</p>
  </footer>

  <!-- JavaScript -->
  <script>
    // 元素选择器
    const backButton = document.getElementById('back-button');
    const userGender = document.getElementById('user-gender');
    const userAge = document.getElementById('user-age');
    const recognizedChars = document.getElementById('recognized-chars');
    const analysisTime = document.getElementById('analysis-time');
    const analysisResultContainer = document.getElementById('analysis-result');

    // 返回按钮点击事件
    backButton.addEventListener('click', function() {
      window.location.href = 'index.html';
    });

    // 页面加载时获取并显示用户信息
    document.addEventListener('DOMContentLoaded', function() {
      // 从localStorage获取用户信息
      const gender = localStorage.getItem('userGender');
      const age = localStorage.getItem('userAge');
      const chars = localStorage.getItem('recognizedChars');
      const analysisResult = localStorage.getItem('analysisResult');
      
      // 如果有存储的信息，更新页面显示
      if (gender) {
        userGender.textContent = gender;
      }
      if (age) {
        userAge.textContent = age;
      }
      if (chars) {
        recognizedChars.textContent = chars;
      }
      
      // 设置当前时间为分析时间
      const now = new Date();
      const year = now.getFullYear();
      const month = String(now.getMonth() + 1).padStart(2, '0');
      const day = String(now.getDate()).padStart(2, '0');
      const hours = String(now.getHours()).padStart(2, '0');
      const minutes = String(now.getMinutes()).padStart(2, '0');
      const formattedTime = `${year}.${month}.${day} ${hours}:${minutes}`;
      analysisTime.textContent = formattedTime;
      
      // 为元素添加淡入动画延迟
      const fadeElements = document.querySelectorAll('.fade-in');
      fadeElements.forEach((element, index) => {
        element.style.animationDelay = `${index * 0.1}s`;
      });
      
      // 检查是否有待处理的分析任务
      checkAndExecuteAnalysis();
    });
    
    // 检查并执行分析任务
    function checkAndExecuteAnalysis() {
      // 立即显示加载状态和提示信息
      const loadingContainer = document.getElementById('loading-container');
      if (loadingContainer) {
        const loadingText = loadingContainer.querySelector('p:first-of-type');
        if (loadingText) {
          loadingText.textContent = '正在进行深度分析...预计需要2-3分钟时间，请耐心等待';
        }
      }
      
      // 检查是否有存储的分析结果
      const analysisResult = localStorage.getItem('analysisResult');
      const analysisStatus = localStorage.getItem('analysisStatus');
      
      // 如果已经有分析结果，直接渲染
      if (analysisResult) {
        console.log('使用已存储的分析结果');
        renderMarkdown(analysisResult);
        // 清除临时数据
        localStorage.removeItem('analysisStatus');
        localStorage.removeItem('charsForAnalysis');
        localStorage.removeItem('analysisGender');
        localStorage.removeItem('analysisAge');
        localStorage.removeItem('analysisAttempt');
        localStorage.removeItem('maxAnalysisAttempts');
        return;
      }
      
      // 获取分析所需的数据
      const charsForAnalysis = localStorage.getItem('charsForAnalysis');
      const analysisGender = localStorage.getItem('analysisGender');
      const analysisAge = localStorage.getItem('analysisAge');
      const analysisAttempt = parseInt(localStorage.getItem('analysisAttempt') || '1');
      const maxAnalysisAttempts = parseInt(localStorage.getItem('maxAnalysisAttempts') || '3');
      
      // 执行分析工作流API调用
      if (charsForAnalysis && analysisGender && analysisAge) {
        console.log('开始执行分析工作流API调用...');
        console.log('分析数据:', { chars: charsForAnalysis, gender: analysisGender, age: analysisAge });
        console.log('尝试次数:', analysisAttempt, '/', maxAnalysisAttempts);
        executeAnalysisWorkflow(charsForAnalysis, analysisGender, analysisAge, analysisAttempt, maxAnalysisAttempts);
      } else {
        // 没有足够的分析数据，显示错误信息
        const resultContent = document.getElementById('result-content');
        if (resultContent) {
          resultContent.innerHTML = [
            '<div class="markdown-container">',
            '<h3 class="text-lg font-bold text-primary mb-4">标准报告</h3>',
            '<div class="space-y-4 text-gray-700 leading-relaxed">',
            '<p class="text-red-600">分析数据不完整，请重新开始测评</p>',
            '<p class="text-gray-600">请返回首页重新进行测试。</p>',
            '</div>',
            '</div>'
          ].join('');
          resultContent.classList.remove('hidden');
        }
        if (loadingContainer) {
          loadingContainer.classList.add('hidden');
        }
        console.error('缺少分析所需数据:', { charsForAnalysis, analysisGender, analysisAge });
      }
    }
    
    // 执行分析工作流，调用实际API
    function executeAnalysisWorkflow(chars, gender, age, attempt, maxAttempts) {
      console.log('===== 执行分析工作流API调用 (尝试', attempt, '/', maxAttempts, ') =====');
      
      // Coze API配置
      const COZE_API_KEY = 'pat_SlLREElBSRnO5GVL8nopClZaMqoyMScm0idEOg6e7X6v1lM7mSG9O3HF5zOP8qH1';
      const COZE_WORKFLOW_ENDPOINT = 'https://api.coze.cn/v1/workflow/run';
      
      // 更新加载提示，显示当前尝试次数
      const loadingContainer = document.getElementById('loading-container');
      if (loadingContainer) {
        const loadingText = loadingContainer.querySelector('p:first-of-type');
        if (loadingText) {
          if (attempt > 1) {
            loadingText.textContent = '正在进行深度分析...（正在进行第' + attempt + '次尝试）';
          } else {
            loadingText.textContent = '正在进行深度分析...预计需要2-3分钟时间，请耐心等待';
          }
        }
      }
      
      // 准备分析工作流请求数据
      const requestData = {
        workflow_id: '7565444904600944692', // 分析工作流ID
        parameters: {
          words: chars,
          gender: gender,
          age: age
        },
        user_id: 'user_' + Date.now() + '_' + attempt
      };
      
      // 使用XHR发送请求
      const xhr = new XMLHttpRequest();
      xhr.open('POST', COZE_WORKFLOW_ENDPOINT, true);
      xhr.setRequestHeader('Authorization', 'Bearer ' + COZE_API_KEY);
      xhr.setRequestHeader('Content-Type', 'application/json');
      xhr.timeout = 300000; // 5分钟超时
      
      xhr.onload = function() {
        console.log('分析工作流响应状态:', xhr.status);
        console.log('分析工作流响应文本:', xhr.responseText);
        
        try {
          const responseData = JSON.parse(xhr.responseText);
          console.log('分析工作流响应数据:', responseData);
          
          if (xhr.status === 200 && responseData.code === 0) {
            // 成功获取分析结果
            let analysisResult = '';
            try {
              const parsedData = typeof responseData.data === 'string' ? 
                JSON.parse(responseData.data) : responseData.data;
              analysisResult = parsedData.output || JSON.stringify(parsedData);
            } catch (e) {
              analysisResult = responseData.data || JSON.stringify(responseData);
            }
            
            console.log('分析结果获取成功！');
            // 存储分析结果
            localStorage.setItem('analysisResult', analysisResult);
            localStorage.setItem('analysisStatus', 'completed');
            
            // 渲染分析结果
            renderMarkdown(analysisResult);
            
            // 清除临时数据
            localStorage.removeItem('charsForAnalysis');
            localStorage.removeItem('analysisGender');
            localStorage.removeItem('analysisAge');
            localStorage.removeItem('analysisAttempt');
            localStorage.removeItem('maxAnalysisAttempts');
          } else {
            // API返回错误
            const errorMsg = responseData.msg || '未知错误 (状态码: ' + xhr.status + ')';
            console.error('分析工作流执行错误:', errorMsg);
            
            // 检查是否需要重试
            if (attempt < maxAttempts) {
              console.log('分析失败，', attempt, '秒后第', attempt + 1, '次重试...');
              setTimeout(function() {
                executeAnalysisWorkflow(chars, gender, age, attempt + 1, maxAttempts);
              }, 1000 * attempt);
            } else {
              // 显示错误信息
              showAnalysisError('分析失败: ' + errorMsg);
            }
          }
        } catch (parseError) {
          // JSON解析错误
          console.error('分析工作流响应解析错误:', parseError);
          
          // 检查是否需要重试
          if (attempt < maxAttempts) {
            console.log('解析错误，', attempt, '秒后第', attempt + 1, '次重试...');
            setTimeout(function() {
              executeAnalysisWorkflow(chars, gender, age, attempt + 1, maxAttempts);
            }, 1000 * attempt);
          } else {
            showAnalysisError('分析响应解析错误: ' + parseError.message);
          }
        }
      };
      
      xhr.onerror = function() {
        console.error('分析工作流网络错误');
        
        // 检查是否需要重试
        if (attempt < maxAttempts) {
          console.log('网络错误，', attempt, '秒后第', attempt + 1, '次重试...');
          setTimeout(function() {
            executeAnalysisWorkflow(chars, gender, age, attempt + 1, maxAttempts);
          }, 1000 * attempt);
        } else {
          showAnalysisError('网络连接错误，请检查您的网络连接');
        }
      };
      
      xhr.ontimeout = function() {
        console.error('分析工作流请求超时');
        
        // 检查是否需要重试
        if (attempt < maxAttempts) {
          console.log('请求超时，', attempt, '秒后第', attempt + 1, '次重试...');
          setTimeout(function() {
            executeAnalysisWorkflow(chars, gender, age, attempt + 1, maxAttempts);
          }, 1000 * attempt);
        } else {
          showAnalysisError('请求超时，请稍后重试');
        }
      };
      
      // 发送请求
      xhr.send(JSON.stringify(requestData));
    }
    

    
    // 显示分析错误信息
    function showAnalysisError(errorMessage) {
      const resultContent = document.getElementById('result-content');
      const loadingContainer = document.getElementById('loading-container');
      
      // 显示错误信息
      if (resultContent) {
        resultContent.innerHTML = [
          '<div class="markdown-container">',
          '<h3 class="text-lg font-bold text-primary mb-4">标准报告</h3>',
          '<div class="space-y-4 text-gray-700 leading-relaxed">',
          '<p class="text-red-600">' + errorMessage + '</p>',
          '<p class="text-gray-600">请稍后重试或返回上一页重新提交分析。</p>',
          '<button id="retry-analysis" class="mt-4 px-6 py-2 bg-primary text-white font-medium rounded-md hover:bg-primary/90 transition-colors">',
          '  重新分析',
          '</button>',
          '</div>',
          '</div>'
        ].join('');
        resultContent.classList.remove('hidden');
        
        // 添加重试按钮事件
        document.getElementById('retry-analysis').addEventListener('click', function() {
          // 重置尝试次数并重新执行分析
          localStorage.setItem('analysisAttempt', '1');
          const charsForAnalysis = localStorage.getItem('charsForAnalysis');
          const analysisGender = localStorage.getItem('analysisGender');
          const analysisAge = localStorage.getItem('analysisAge');
          const maxAnalysisAttempts = parseInt(localStorage.getItem('maxAnalysisAttempts') || '3');
          
          // 重新显示loading
          if (loadingContainer) {
            loadingContainer.classList.remove('hidden');
          }
          resultContent.classList.add('hidden');
          
          // 重新执行分析
          executeAnalysisWorkflow(charsForAnalysis, analysisGender, analysisAge, 1, maxAnalysisAttempts);
        });
      }
      
      // 隐藏loading
      if (loadingContainer) {
        loadingContainer.classList.add('hidden');
      }
      
      // 更新状态
      localStorage.setItem('analysisStatus', 'error');
    }

    // 渲染markdown内容
    function renderMarkdown(markdown) {
      try {
        // 获取元素引用
        const loadingContainer = document.getElementById('loading-container');
        const resultContent = document.getElementById('result-content');
        
        // 设置marked选项
        marked.setOptions({
          breaks: true,
          gfm: true,
          headerIds: false,
          mangle: false
        });
        
        // 转换markdown为HTML
        const htmlContent = marked.parse(markdown);
        
        // 检查是否有标题，如果没有，添加默认标题
        if (!htmlContent.includes('<h')) {
          resultContent.innerHTML = [
            '<div class="markdown-container">',
            '<h3 class="text-lg font-bold text-primary mb-4">标准报告</h3>',
            '<div class="space-y-4 text-gray-700 leading-relaxed">',
            htmlContent,
            '</div>',
            '</div>'
          ].join('');
        } else {
          resultContent.innerHTML = [
            '<div class="markdown-container">',
            '<div class="space-y-4 text-gray-700 leading-relaxed">',
            htmlContent,
            '</div>',
            '</div>'
          ].join('');
        }
        
        // 为渲染后的内容添加样式
          applyCustomStyles();
          
          // 隐藏loading，显示结果
        if (loadingContainer) {
          loadingContainer.classList.add('hidden');
        }
        if (resultContent) {
          resultContent.classList.remove('hidden');
        }
      } catch (error) {
        console.error('Markdown渲染错误:', error);
        
        // 获取元素引用
        const loadingContainer = document.getElementById('loading-container');
        const resultContent = document.getElementById('result-content');
        
        // 显示错误信息
        resultContent.innerHTML = [
          '<div class="markdown-container">',
          '<h3 class="text-lg font-bold text-primary mb-4">标准报告</h3>',
          '<div class="space-y-4 text-gray-700 leading-relaxed">',
          '<p class="text-red-600">分析结果渲染失败</p>',
          '<p class="text-gray-500 text-sm">原始内容：</p>',
          '<pre class="bg-gray-100 p-3 rounded text-sm overflow-x-auto">' + 
          markdown.replace(/</g, '&lt;').replace(/>/g, '&gt;') + 
          '</pre>',
          '</div>',
          '</div>'
        ].join('');
          
          // 隐藏loading，显示错误
        if (loadingContainer) {
          loadingContainer.classList.add('hidden');
        }
        if (resultContent) {
          resultContent.classList.remove('hidden');
        }
      }
    }

    // 应用自定义样式
    function applyCustomStyles() {
      // 为h2添加样式
      const h2Elements = analysisResultContainer.querySelectorAll('h2');
      h2Elements.forEach(el => {
        el.classList.add('text-xl', 'font-bold', 'text-primary', 'mt-6', 'mb-3');
      });
      
      // 为h3添加样式
      const h3Elements = analysisResultContainer.querySelectorAll('h3');
      h3Elements.forEach(el => {
        el.classList.add('text-lg', 'font-bold', 'text-primary', 'mt-4', 'mb-2');
      });
      
      // 为段落添加样式
      const pElements = analysisResultContainer.querySelectorAll('p');
      pElements.forEach(el => {
        el.classList.add('leading-relaxed', 'text-gray-700');
      });
      
      // 为列表添加样式
      const ulElements = analysisResultContainer.querySelectorAll('ul');
      ulElements.forEach(el => {
        el.classList.add('list-disc', 'pl-5', 'space-y-1', 'text-gray-700');
      });
      
      const olElements = analysisResultContainer.querySelectorAll('ol');
      olElements.forEach(el => {
        el.classList.add('list-decimal', 'pl-5', 'space-y-1', 'text-gray-700');
      });
      
      // 为强调文本添加样式
      const strongElements = analysisResultContainer.querySelectorAll('strong');
      strongElements.forEach(el => {
        el.classList.add('font-medium', 'text-primary');
      });
    }

    // 分享按钮功能（模拟）
    document.querySelectorAll('.w-12.h-12.bg-blue-100').forEach(button => {
      button.addEventListener('click', function() {
        const platform = this.nextElementSibling.textContent;
        alert(`分享到${platform}功能已触发！`);
      });
    });
  </script>
</body>
</html>